import schedule
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains

# 初始化 Selenium WebDriver
# stat_time = time.time()
options = webdriver.ChromeOptions()
options.add_argument("--disable-gpu")  # 可选：减少资源消耗
driver = webdriver.Chrome(options=options)
# end_time = time.time()
# print(end_time - stat_time)


def fill_form():
    try:
        # 打开问卷页面
        url = "https://www.wjx.top/vm/tope34P.aspx"
        driver.get(url)

        # 等待页面加载完成
        time.sleep(1)

        # 找到并点击“立即报名”按钮
        signup_button = driver.find_element(By.CSS_SELECTOR, '#slideChunk .slideChunkWord')
        ActionChains(driver).move_to_element(signup_button).click().perform()
        print("点击了立即报名按钮")

        # 等待页面加载表单
        time.sleep(1)

        # 获取所有可能的字段
        fields = driver.find_elements(By.XPATH, "//div[contains(@class, 'field ui-field-contain')]")

        # 定义字段的映射变量
        student_id_field = None
        name_field = None
        radio_option_selected = False  # 用于标记是否已选择人工智能学院

        # 遍历字段，查找对应的学号和姓名
        for field in fields:
            label = field.find_element(By.CLASS_NAME, 'topichtml').text
            input_elements = field.find_elements(By.TAG_NAME, 'input')

            if "学号" in label:
                student_id_field = input_elements[0]
            elif "姓名" in label:
                name_field = input_elements[0]
            elif input_elements and input_elements[0].get_attribute("type") == "radio":
                # 检测到单选框类型，检查其选项是否包含“人工智能学院”
                options = field.find_elements(By.CLASS_NAME, 'ui-radio')
                for option in options:
                    option_label = option.find_element(By.CLASS_NAME, 'label').text
                    if "人工智能学院" in option_label:
                        radio_button = option.find_element(By.TAG_NAME, 'a')  # 获取单选按钮元素
                        radio_button.click()  # 选择该单选项
                        print("已选择人工智能学院选项")
                        radio_option_selected = True
                        break
            # 如果已经选择单选框，就不需要继续检查其他单选框
            if radio_option_selected:
                break

        # 检查是否找到学号和姓名字段
        if student_id_field and name_field:
            # 填写学号和姓名
            student_id_field.send_keys("2023024330")
            name_field.send_keys("薛国鹏")
            print("已填写学号和姓名")

            # 提交表单
            submit_button = driver.find_element(By.XPATH, '//*[@id="ctlNext"]')
            ActionChains(driver).move_to_element(submit_button).click().perform()
            print("表单已提交")
        else:
            print("未找到学号或姓名字段，请检查表单结构")

        # 等待提交结果
        time.sleep(1)

    finally:
        # 关闭浏览器
        driver.quit()


# 设置定时任务，晚上 8 点 50 执行
schedule.every().day.at("21:51").do(fill_form)

print("等待执行任务...")

while True:
    # 运行所有设置的定时任务
    schedule.run_pending()
    # 延迟一秒钟检查一次
    time.sleep(1)
